package twitter.RequestParser;

import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/***************************************************
 * this class is designed for read all the response the front 
 * end server receives from the back end server
 * @author fang
 *
 */

public class XMLReader {
	
	/************************************************
	 * read response of post a new status
	 *  <response>success</response>
	 * @param doc_response
	 * @return
	 */
	public String readResponseFromPost(Document doc_response)
	{
		String result="";
		
		Node response = doc_response.getFirstChild();
		
		result=response.getTextContent();
		
		return result;
	}

	/**************************************************
	 * read response of get request from back end server
	 * response: <responses tag="tag"> <response status="status1" version="1" >
	 * </response> <response status="status2" version="2" > </response>
	 * </responses>
	 */
	public HashMap<String, ArrayList<String>> readStatusFromResponse(
			Document DOC_response) {
		ArrayList<String> statusResult = new ArrayList<String>();
		ArrayList<String> versionResult = new ArrayList<String>();
		ArrayList<String> tagResult = new ArrayList<String>();
		Node tweets = DOC_response.getFirstChild();
		
		NamedNodeMap tagAtts = tweets.getAttributes();
		Node tag = tagAtts.getNamedItem("tag");
		tagResult.add(tag.getNodeValue());
		NodeList responses = tweets.getChildNodes();
		for (int i = 0; i < responses.getLength(); i++) {
			Node response = responses.item(i);
			NamedNodeMap atts = response.getAttributes();
			// for (int j = 0; j < atts.getLength(); j++) {
			Node att = atts.getNamedItem("status");
			statusResult.add(att.getNodeValue());
			Node version = atts.getNamedItem("version");
			versionResult.add(version.getNodeValue());
			// }
		}
		HashMap<String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();
		hm.put("status", statusResult);
		hm.put("version", versionResult);
		hm.put("tag", tagResult);
		return hm;
	}

	
	

	/****************************************************
	 * read response of get request from back end server
	 * <responses> <response maxversion="max" tag="tag"> </response>
	 * </responses>
	 */
	public int readMaxVersionFromResponse(Document Doc_response) {
		int result = -1;
		Node responses = Doc_response.getFirstChild();
		Node rep = responses.getFirstChild();
		NamedNodeMap atts = rep.getAttributes();

		Node att = atts.getNamedItem("maxversion");
		result = Integer.parseInt(att.getNodeValue());

		return result;
	}
}
